<template>
  <div class="dashboard-container">
    <h1 style="text-align: center">订房管理</h1>

    <el-dialog title="入住" :visible.sync="updateButtonController" width="30%" @close="closeReserve('ruleForm')">
      <el-form label-width="20%" ref="ruleForm">
        <p style="text-align: center; font-size: 16px;">确认是否入住</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="updateAllReserve('ruleForm')">确 定</el-button>
        <el-button plain @click="closeReserve('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="取消" :visible.sync="cancelReserveController" width="30%" @close="closeCancelReserve('ruleForm')">
      <el-form label-width="20%" ref="ruleForm">
        <p style="text-align: center; font-size: 16px;">确认是否取消</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="cancelAllReserve('ruleForm')">确 定</el-button>
        <el-button plain @click="closeCancelReserve('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>


    <el-dialog title="作废" :visible.sync="abrogateReserveController" width="30%" @close="closeAbrogate('ruleForm')">
      <el-form label-width="20%" ref="ruleForm">
        <p style="text-align: center; font-size: 16px;">确认是否作废</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="abrogateAllReserve('ruleForm')">确 定</el-button>
        <el-button plain @click="closeAbrogate('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="新增"
      :visible.sync="addButtonController"
      width="50%"
      @close="closeReserve('ruleForm')"
    >
      <el-form label-width="20%" :model="addList" :rules="Reserves" ref="ruleForm">
        <el-form-item label="房间" prop="roomId">
          <el-select v-model="addList.roomId" clearable placeholder="房间" class="full-width">
            <el-option
              v-for="item in roomOptions"
              :key="item.roomId"
              :label="item.roomNumber"
              :value="item.roomId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="顾客" prop="customerId">
          <el-select v-model="addList.customerId" clearable placeholder="顾客" class="full-width">
            <el-option
              v-for="item in customerOptions"
              :key="item.customerId"
              :label="item.customerName + '-' + item.identificationCard"
              :value="item.customerId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入住时间" prop="reserveLiveTime">
          <el-date-picker
            v-model="addList.reserveLiveTime"
            type="date"
            placeholder="请选择入住日期"
            value-format="yyyy-MM-dd"
            class="full-width"
            clearable
          />
        </el-form-item>
        <el-form-item label="入住天数" prop="reserveDayNumber">
          <el-input v-model="addList.reserveDayNumber" show-word-limit class="full-width"
                    clearable
                    placeholder="请输入您要入住的天数"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addList.remark"  show-word-limit class="full-width" clearable
                    placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="addReserve('ruleForm')">确 定</el-button>
    <el-button @click="closeReserve('ruleForm')">取 消</el-button>
  </span>
    </el-dialog>
    <el-button plain
               style="width:80px;margin-bottom:30px;margin-left:18% ;background-color: #cfefc6; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);"
               @click="addButton"
    >
      新增
    </el-button>
    <el-select v-model="state" clearable placeholder="预定状态" style="margin-left: 40px;width: 200px">
      <el-option
        v-for="item in stateOptions"
        :key="item.state"
        :label="item.state"
        :value="item.state"
      />
    </el-select>

    <el-input
      v-model="roomNumber"
      placeholder="房间号"
      name="roomNumber"
      type="text"
      clearable
      style="margin-left:40px ;width: 180px"
    />

    <el-input
      v-model="reserveId"
      placeholder="预定ID"
      name="roomNumber"
      type="text"
      clearable
      style="margin-left:40px ;width: 180px"
    />


    <el-button plain
               style="width:80px;margin-bottom:30px;margin-left:40px ;background-color: #cfefc6; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);"
               @click="selectAll"
    >
      查询
    </el-button>
    <el-button
      style="width:80px;margin-bottom:30px;margin-left:40px ;background-color: white; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);"
      @click="checkReserve"
    >重置
    </el-button>
    <el-table :data="reserveList.slice((currentPage-1)*pagesize,currentPage*pagesize)" height="659px" border style="width: 100%;margin-top: 20px"
              class="elegant-room-table"
    >
      <el-table-column align="center" fixed prop="reserveId" label="预定ID" min-width="100"/>
      <el-table-column align="center" fixed prop="roomNumber" label="房间号" min-width="100"/>
      <el-table-column align="center" fixed prop="customerName" label="顾客名称" width="100"/>
      <el-table-column align="center" fixed prop="identificationCard" label="身份证号" width="160"/>
      <el-table-column align="center" fixed prop="state" label="房间状态" min-width="130">
        <template v-slot="scope">
    <span :class="{
        'state-green': ['空闲', '预定中'].includes(scope.row.state),
        'state-red': scope.row.state === '已入住'
      }">
      {{ scope.row.state }}
    </span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed prop="liveId" label="订单ID" min-width="100"/>
      <el-table-column align="center" fixed prop="reserveTime" label="预定时间" min-width="120"/>
      <el-table-column align="center" fixed prop="reserveLiveTime" label="入住时间" width="120"/>
      <el-table-column align="center" fixed prop="reserveDayNumber" label="入住天数" width="100"/>
      <el-table-column align="center" fixed prop="remark" label="备注" width="130"/>
      <el-table-column align="center" fixed prop="abrogateIdentity" label="作废标识" width="110"/>
      <el-table-column align="center" fixed label="操作" width="150">
        <template v-slot="scope">
          <el-button type="text" v-if="scope.row.state === '预定中' && scope.row.abrogateIdentity != '已作废'" @click="updateButton(scope.row)">入住</el-button>
          <el-button type="text" v-if="scope.row.state === '预定中' && scope.row.abrogateIdentity != '已作废'" @click="cancelReserveButton(scope.row)">取消</el-button>
          <el-button type="text" v-if="scope.row.state === '预定中' && scope.row.abrogateIdentity != '已作废'" @click="abrogateReserveButton(scope.row)">作废</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:5px;margin-left: 30%;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,8,10,15,20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="reserveList.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { deleteRoomType, insert1RoomType, selectAllRoomType, updateRoomType } from '@/api/roomType'
import { insertCustomer, selectAllCustomer, updateCustomer } from '@/api/customer'
import { selectAllLiveRecords } from '@/api/liveRecords'
import { selectAllStay1 } from '@/api/stay'
import { abrogateReserve1, cancelReserve1, insertReserve, selectAllReserve, updateReserve1 } from '@/api/reserve'
import { selectAllRoom } from '@/api/room'

export default {
  name: 'user',
  computed: {
    ...mapGetters([
      'userId',
      'userName',
      'roleName'
    ])
  },
  data() {
    return {
      state: '',
      roomNumber: '',
      reserveId: '',
      reserveList: [],
      addButtonController: false,
      updateButtonController:false,
      abrogateReserveController:false,
      cancelReserveController:false,
      // 下拉数据
      roomOptions: [],
      customerOptions: [],
      stateOptions: [],
      currentPage: 1,
      currentIndex: '',
      pagesize: 8,
      addList: {
        customerId:'',
        roomId:'',
        roomNumber: '',
        customerName: '',
        reserveLiveTime: '',
        identificationCard:'',
        reserveDayNumber: '',
        remark: ''
      },
      updateList:{
        liveId:'',
      },
      abrogateReserveList:{
        abrogateIdentity:'',
      },
      cancelReserveTableId:'',
      cancelReserveId:'',
      Reserves: {
        // 校验规则示例
        roomId: [
          { required: true, message: '请选择房间', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择顾客', trigger: 'change' }
        ],
        reserveLiveTime: [
          { required: true, message: '请选择入住日期', trigger: 'change' }
        ],
        reserveDayNumber: [
          { required: true, message: '请输入入住天数', trigger: 'blur' },
          { validator: this.validateReserveDayNumber, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.selectAll()
    this.fetchRoomOptions()
    this.fetchCustomerOptions()
    this.fetchStateOptions()
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage= val
    },
    validateReserveDayNumber(rule, value, callback) {
      if (!value || isNaN(value)) {
        callback(new Error('入住天数必须为数字'))
      } else if (value < 1 || value > 366) {
        callback(new Error('入住天数必须在1到366天之间'))
      } else {
        callback()
      }
    },
    selectAll() {
      selectAllReserve({
        state: this.state,
        roomNumber: this.roomNumber,
        reserveId: this.reserveId
      }).then(
        response => {
          console.log(response.data)
          this.reserveList = response.data.filter(item => item.state !== '已取消');
          if((this.reserveList.slice((this.currentPage-1)*this.pagesize,this.currentPage*this.pagesize)).length == 0){
            this.currentPage = 1
          }
        }
      )
    },
    addReserve(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          insertReserve({
            customerId:this.addList.customerId,
            roomId:this.addList.roomId,
            roomNumber: this.addList.roomNumber,
            customerName: this.addList.customerName,
            identificationCard:this.addList.identificationCard,
            reserveLiveTime: this.addList.reserveLiveTime,
            reserveDayNumber: this.addList.reserveDayNumber,
            remark: this.addList.remark
          }).then(
            response => {
              this.addButtonController = false
              this.$message.success('新增成功！')
              this.selectAll()
            }
          )
        } else {
          return false
        }
      })
    },
    updateAllReserve(formName) {
      updateReserve1({
        liveId: this.updateList.liveId,
        reserveTableId: this.updateList.reserveTableId,
      }).then(response => {
        this.updateButtonController = false;
        this.$message.success('入住成功');
        this.selectAll();
      }).catch(error => {
        console.error(error);
        this.$message.error('入住失败');
      });
    },
    cancelAllReserve(formName) {
      cancelReserve1({
        reserveId:this.cancelReserveId,
        reserveTableId:this.cancelReserveTableId
      }).then(response => {
        this.cancelReserveController = false;
        this.$message.success('取消成功');
        this.selectAll();
      });
    },
    abrogateAllReserve(formName) {
      abrogateReserve1({
        abrogateIdentity:this.abrogateReserveList.abrogateIdentity,
        reserveTableId:this.abrogateReserveList.reserveTableId
      }).then(response => {
        this.abrogateReserveController = false;
        this.$message.success('作废成功');
        this.selectAll();
      }).catch(error => {
        console.error(error);
        this.$message.error('作废失败');
      });
    },
    // fetchRoomOptions() {
    //   selectAllRoom().then(response => {
    //     this.roomOptions = Object.values(
    //       response.data.reduce((selectRoomId, item) => {
    //         selectRoomId[item.roomId] = item; // 保留最后一个出现的重复项
    //         return selectRoomId;
    //       }, {})
    //     );
    //   });
    // },
    fetchRoomOptions() {
      selectAllRoom()
        .then(response => {
          const roomMap = response.data.reduce((acc, item) => {
            acc[item.roomId] = item; // 按 roomId 去重，保留最后一个出现的项
            return acc;
          }, {});
          this.roomOptions = Object.values(roomMap);
        })
        .catch(error => {
          console.error('获取房间选项失败:', error);
          this.roomOptions = []; // 可选：失败时清空或设默认值
        });
    },
    fetchCustomerOptions() {
      selectAllCustomer().then(response => {
        this.customerOptions = response.data.map(customer => ({
          customerId: customer.customerId,
          customerName: customer.customerName,
          identificationCard: customer.identificationCard
        }));
      });
    },
    fetchStateOptions() {
      selectAllReserve().then(response => {
        const uniqueStatees = new Set(response.data.map(item => item.state))
        this.stateOptions = [...uniqueStatees].map(state => ({ state }))
      }).catch(() => {
        this.$message.error('获取状态列表失败')
      })
    },
    checkReserve() {
      this.state = ''
      this.roomNumber = ''
      this.reserveId = ''
      this.selectAll()
    },
    addButton() {
      this.addList = {
        customerId:'',
        roomId: '',
        roomNumber: '',
        customerName: '',
        identificationCard:'',
        reserveLiveTime: '',
        reserveDayNumber: '',
        remark: ''
      }
      this.addButtonController = true
    },
    updateButton(row){
      this.updateList={
        liveId: '',
        reserveTableId:row.reserveTableId,
      }
      this.updateButtonController = true
    },
    abrogateReserveButton(row){
      this.abrogateReserveList={
        abrogateIdentity: '',
        reserveTableId: row.reserveTableId
      }
      this.abrogateReserveController = true
    },
    cancelReserveButton(row){
      this.cancelReserveTableId = row.reserveTableId
      this.cancelReserveId = row.reserveId
      this.cancelReserveController = true
    },
    closeReserve(formName) {
      this.$refs[formName].resetFields()
      this.addButtonController = false
      this.updateButtonController = false
    },
    closeCancelReserve(){
      this.cancelReserveController = false;
    },
    closeAbrogate(){
      this.abrogateReserveController = false;
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.elegant-room-table {
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  overflow: hidden;

  &::before {
    display: none;
  }

  .price-tag {
    display: inline-block;
    padding: 3px 8px;
    color: #171717;
    border-radius: 12px;
    font-weight: 500;
  }
}

.full-width {
  width: 88%;
}

.state-green {
  color: green;
}

.state-red {
  color: red;
}
</style>
